@{
    ViewData["Title"] = "修改生产计划";
}

<link href="~/layui/css/layui.css" rel="stylesheet" />

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h5 class="mb-0">
                                <i class="layui-icon layui-icon-form"></i>
                                修改生产计划
                            </h5>
                        </div>
                        <div class="col-md-6 text-end">
                            <button type="button" class="btn btn-secondary" onclick="goBack()">
                                <i class="layui-icon layui-icon-return"></i>
                                返回
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="card-body">
                    <form id="productionPlanForm">
                        <input type="hidden" id="planId" name="planId" value="0">
                        
                        <!-- 基本信息 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h6 class="border-bottom pb-2 mb-3">
                                    <i class="layui-icon layui-icon-form"></i>
                                    基本信息
                                </h6>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="planSubject" class="form-label">计划主题 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="planSubject" name="planSubject" 
                                       placeholder="请输入计划主题" required>
                            </div>
                            <div class="col-md-6">
                                <label for="planOrderNumber" class="form-label">计划单号 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="planOrderNumber" name="planOrderNumber" 
                                       placeholder="请输入计划单号" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="salesOrderNumber" class="form-label">销售订单号</label>
                                <input type="text" class="form-control" id="salesOrderNumber" name="salesOrderNumber" 
                                       placeholder="请输入销售订单号">
                            </div>
                            <div class="col-md-6">
                                <label for="relatedProjectName" class="form-label">关联项目</label>
                                <input type="text" class="form-control" id="relatedProjectName" name="relatedProjectName" 
                                       placeholder="请输入关联项目名称">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="productionLine" class="form-label">生产线</label>
                                <input type="text" class="form-control" id="productionLine" name="productionLine" 
                                       placeholder="请输入生产线">
                            </div>
                            <div class="col-md-6">
                                <label for="documentDate" class="form-label">单据日期 <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="documentDate" name="documentDate" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="expectedStartDate" class="form-label">计划开始时间 <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control" id="expectedStartDate" name="expectedStartDate" required>
                            </div>
                            <div class="col-md-6">
                                <label for="expectedEndDate" class="form-label">计划结束时间 <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control" id="expectedEndDate" name="expectedEndDate" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="planStatus" class="form-label">计划状态 <span class="text-danger">*</span></label>
                                <select class="form-select" id="planStatus" name="planStatus" required>
                                    <option value="">请选择计划状态</option>
                                    <option value="0">草稿</option>
                                    <option value="1">已下达</option>
                                    <option value="2">执行中</option>
                                    <option value="3">已完成</option>
                                    <option value="4">已取消</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="priority" class="form-label">优先级 <span class="text-danger">*</span></label>
                                <select class="form-select" id="priority" name="priority" required>
                                    <option value="">请选择优先级</option>
                                    <option value="1">低</option>
                                    <option value="2">中</option>
                                    <option value="3">高</option>
                                    <option value="4">紧急</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-12">
                                <label for="remarks" class="form-label">备注</label>
                                <textarea class="form-control" id="remarks" name="remarks" rows="3" 
                                          placeholder="请输入备注信息"></textarea>
                            </div>
                        </div>

                        <!-- 生产项目 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h6 class="border-bottom pb-2 mb-3">
                                    <i class="layui-icon layui-icon-list"></i>
                                    生产项目
                                    <button type="button" class="btn btn-sm btn-primary ms-2" onclick="addProductionItem()">
                                        <i class="layui-icon layui-icon-add-1"></i>
                                        添加项目
                                    </button>
                                </h6>
                            </div>
                        </div>
                        
                        <div class="table-responsive mb-3">
                            <table class="table table-bordered" id="productionItemsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th width="120">项目编号</th>
                                        <th width="150">项目名称</th>
                                        <th width="120">规格型号</th>
                                        <th width="80">单位</th>
                                        <th width="100">物品分类</th>
                                        <th width="100">物品类别</th>
                                        <th width="100">品牌</th>
                                        <th width="100">数量</th>
                                        <th width="100">计划数量</th>
                                        <th width="100">已完成数量</th>
                                        <th width="80">排序</th>
                                        <th width="80">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="productionItemsBody">
                                    <!-- 动态添加的生产项目行 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 附件信息 -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h6 class="border-bottom pb-2 mb-3">
                                    <i class="layui-icon layui-icon-upload"></i>
                                    附件信息
                                    <button type="button" class="btn btn-sm btn-primary ms-2" onclick="addAttachment()">
                                        <i class="layui-icon layui-icon-add-1"></i>
                                        添加附件
                                    </button>
                                </h6>
                            </div>
                        </div>
                        
                        <div class="table-responsive mb-3">
                            <table class="table table-bordered" id="attachmentsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th width="200">文件名</th>
                                        <th width="100">文件大小</th>
                                        <th width="200">文件路径</th>
                                        <th width="100">文件类型</th>
                                        <th width="150">上传时间</th>
                                        <th width="100">上传人</th>
                                        <th width="80">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="attachmentsBody">
                                    <!-- 动态添加的附件行 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="row">
                            <div class="col-12 text-center">
                                <button type="button" class="btn btn-primary me-3" onclick="updateProductionPlan()">
                                    <i class="layui-icon layui-icon-ok"></i>
                                    保存修改
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                    <i class="layui-icon layui-icon-refresh"></i>
                                    重置
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        let productionItemIndex = 0;
        let attachmentIndex = 0;
        let currentPlanId = 0;

        // 页面加载完成后初始化
        $(document).ready(function() {
            initializeForm();
            loadPlanData();
        });



        // 初始化表单
        function initializeForm() {
            // 从URL参数获取planId
            const urlParams = new URLSearchParams(window.location.search);
            currentPlanId = urlParams.get('planId') || 0;
            
            if (currentPlanId) {
                $('#planId').val(currentPlanId);
            }
        }

        // 加载生产计划数据
        function loadPlanData() {
            if (!currentPlanId) {
                showError('缺少计划ID参数');
                return;
            }

            // console.log('开始加载生产计划数据，planId:', currentPlanId);
            showLoading();

            $.ajax({
                url: `http://localhost:5025/api/Plan/GetProductionPlanById/${currentPlanId}`,
                type: 'GET',
                timeout: 10000,
                success: function(response) {
                    console.log('API响应:', response);
                    
                    if (response.code === 200 && response.data) {
                        populateForm(response.data);
                    } else {
                        showError('加载生产计划失败：' + (response.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('API请求失败:', {xhr, status, error});
                    let errorMessage = '请求失败：' + error;
                    
                    // 处理不同的错误状态
                    if (xhr.status === 404) {
                        errorMessage = '未找到指定的生产计划，请检查计划ID是否正确';
                    } else if (xhr.status === 500) {
                        errorMessage = '服务器内部错误，请稍后重试';
                    } else if (xhr.status === 0) {
                        errorMessage = '网络连接失败，请检查网络连接或API服务是否启动';
                    }
                    
                    showError(errorMessage);
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 填充表单数据
        function populateForm(plan) {
            // console.log('填充表单数据:', plan);
            
            // 基本信息
            $('#planId').val(plan.planId || 0);
            $('#planSubject').val(plan.planSubject || '');
            $('#planOrderNumber').val(plan.planOrderNumber || '');
            $('#salesOrderNumber').val(plan.salesOrderNumber || '');
            $('#relatedProjectName').val(plan.relatedProjectName || '');
            $('#productionLine').val(plan.productionLine || '');
            $('#remarks').val(plan.remarks || '');
            $('#planStatus').val(plan.planStatus || '');
            $('#priority').val(plan.priority || '');

            // 设置日期
            if (plan.documentDate) {
                try {
                    const docDate = new Date(plan.documentDate);
                    $('#documentDate').val(docDate.toISOString().split('T')[0]);
                } catch (e) {
                    console.warn('文档日期格式错误:', plan.documentDate);
                }
            }
            
            if (plan.expectedStartDate) {
                try {
                    const startDate = new Date(plan.expectedStartDate);
                    $('#expectedStartDate').val(startDate.toISOString().slice(0, 16));
                } catch (e) {
                    console.warn('开始日期格式错误:', plan.expectedStartDate);
                }
            }
            
            if (plan.expectedEndDate) {
                try {
                    const endDate = new Date(plan.expectedEndDate);
                    $('#expectedEndDate').val(endDate.toISOString().slice(0, 16));
                } catch (e) {
                    console.warn('结束日期格式错误:', plan.expectedEndDate);
                }
            }

            // 填充生产项目
            $('#productionItemsBody').empty();
            if (plan.productionItems && plan.productionItems.length > 0) {
                plan.productionItems.forEach((item, index) => {
                    addProductionItemWithData(item, index);
                });
            } else {
                // 如果没有生产项目，添加一个空行
                addProductionItem();
            }

            // 填充附件
            $('#attachmentsBody').empty();
            if (plan.attachments && plan.attachments.length > 0) {
                plan.attachments.forEach((attachment, index) => {
                    addAttachmentWithData(attachment, index);
                });
            }
            
            // console.log('表单数据填充完成');
        }

        // 添加生产项目（带数据）
        function addProductionItemWithData(item, index) {
            // console.log('添加生产项目数据:', item, '索引:', index);
            
            const row = `
                <tr id="productionItem_${index}">
                    <td>
                        <input type="hidden" name="productionItems[${index}].planItemId" value="${item.planItemId || 0}">
                        <input type="hidden" name="productionItems[${index}].planId" value="${item.planId || currentPlanId}">
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].itemNumber" 
                               value="${escapeHtml(item.itemNumber || '')}"
                               placeholder="项目编号">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].itemName" 
                               value="${escapeHtml(item.itemName || '')}"
                               placeholder="项目名称">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].specificationModel" 
                               value="${escapeHtml(item.specificationModel || '')}"
                               placeholder="规格型号">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].unit" 
                               value="${escapeHtml(item.unit || '')}"
                               placeholder="单位">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].itemCategory" 
                               value="${escapeHtml(item.itemCategory || '')}"
                               placeholder="物品分类">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].itemClassification" 
                               value="${escapeHtml(item.itemClassification || '')}"
                               placeholder="物品类别">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${index}].brand" 
                               value="${escapeHtml(item.brand || '')}"
                               placeholder="品牌">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${index}].quantity" 
                               value="${item.quantity || 0}"
                               placeholder="数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${index}].plannedQuantity" 
                               value="${item.plannedQuantity || 0}"
                               placeholder="计划数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${index}].completedQuantity" 
                               value="${item.completedQuantity || 0}"
                               placeholder="已完成数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${index}].sortOrder" 
                               value="${item.sortOrder || index}"
                               placeholder="排序" min="0">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" 
                                onclick="removeProductionItem(${index})">
                            <i class="layui-icon layui-icon-delete"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#productionItemsBody').append(row);
            productionItemIndex = Math.max(productionItemIndex, index + 1);
        }

        // 添加附件（带数据）
        function addAttachmentWithData(attachment, index) {
            // console.log('添加附件数据:', attachment, '索引:', index);
            
            let uploadDateValue = '';
            if (attachment.uploadDate) {
                try {
                    uploadDateValue = new Date(attachment.uploadDate).toISOString().slice(0, 16);
                } catch (e) {
                    console.warn('上传日期格式错误:', attachment.uploadDate);
                }
            }
            
            const row = `
                <tr id="attachment_${index}">
                    <td>
                        <input type="hidden" name="attachments[${index}].attachmentId" value="${attachment.attachmentId || 0}">
                        <input type="hidden" name="attachments[${index}].planId" value="${attachment.planId || currentPlanId}">
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${index}].fileName" 
                               value="${escapeHtml(attachment.fileName || '')}"
                               placeholder="文件名">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="attachments[${index}].fileSize" 
                               value="${attachment.fileSize || 0}"
                               placeholder="文件大小" min="0">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${index}].filePath" 
                               value="${escapeHtml(attachment.filePath || '')}"
                               placeholder="文件路径">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${index}].fileType" 
                               value="${escapeHtml(attachment.fileType || '')}"
                               placeholder="文件类型">
                    </td>
                    <td>
                        <input type="datetime-local" class="form-control form-control-sm" 
                               name="attachments[${index}].uploadDate" 
                               value="${uploadDateValue}"
                               placeholder="上传时间">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${index}].uploadBy" 
                               value="${escapeHtml(attachment.uploadBy || '')}"
                               placeholder="上传人">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" 
                                onclick="removeAttachment(${index})">
                            <i class="layui-icon layui-icon-delete"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#attachmentsBody').append(row);
            attachmentIndex = Math.max(attachmentIndex, index + 1);
        }

        // 添加生产项目
        function addProductionItem() {
            const row = `
                <tr id="productionItem_${productionItemIndex}">
                    <td>
                        <input type="hidden" name="productionItems[${productionItemIndex}].planItemId" value="0">
                        <input type="hidden" name="productionItems[${productionItemIndex}].planId" value="${currentPlanId}">
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemNumber" 
                               placeholder="项目编号">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemName" 
                               placeholder="项目名称">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].specificationModel" 
                               placeholder="规格型号">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].unit" 
                               placeholder="单位">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemCategory" 
                               placeholder="物品分类">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].itemClassification" 
                               placeholder="物品类别">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].brand" 
                               placeholder="品牌">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].quantity" 
                               placeholder="数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].plannedQuantity" 
                               placeholder="计划数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].completedQuantity" 
                               placeholder="已完成数量" min="0">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="productionItems[${productionItemIndex}].sortOrder" 
                               placeholder="排序" min="0" value="${productionItemIndex}">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" 
                                onclick="removeProductionItem(${productionItemIndex})">
                            <i class="layui-icon layui-icon-delete"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#productionItemsBody').append(row);
            productionItemIndex++;
        }

        // 删除生产项目
        function removeProductionItem(index) {
            $(`#productionItem_${index}`).remove();
        }

        // 添加附件
        function addAttachment() {
            const row = `
                <tr id="attachment_${attachmentIndex}">
                    <td>
                        <input type="hidden" name="attachments[${attachmentIndex}].attachmentId" value="0">
                        <input type="hidden" name="attachments[${attachmentIndex}].planId" value="${currentPlanId}">
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].fileName" 
                               placeholder="文件名">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].fileSize" 
                               placeholder="文件大小" min="0">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].filePath" 
                               placeholder="文件路径">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].fileType" 
                               placeholder="文件类型">
                    </td>
                    <td>
                        <input type="datetime-local" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].uploadDate" 
                               placeholder="上传时间">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               name="attachments[${attachmentIndex}].uploadBy" 
                               placeholder="上传人">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" 
                                onclick="removeAttachment(${attachmentIndex})">
                            <i class="layui-icon layui-icon-delete"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#attachmentsBody').append(row);
            attachmentIndex++;
        }

        // 删除附件
        function removeAttachment(index) {
            $(`#attachment_${index}`).remove();
        }

        // 更新生产计划
        function updateProductionPlan() {
            // 表单验证
            if (!validateForm()) {
                return;
            }

            // 收集表单数据
            const formData = collectFormData();
            
            // 验证收集的数据
            if (!formData) {
                return; // collectFormData已经显示了错误信息
            }
            
            // 显示加载状态
            showLoading();

            // 调试：显示发送的数据（可选）
            // console.log('准备发送的数据:', JSON.stringify(formData, null, 2));
            // console.log('planId类型:', typeof formData.planId, '值:', formData.planId);

            // 发送请求
            $.ajax({
                url: 'http://localhost:5025/api/Plan/UpdateProductionPlan',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                timeout: 10000,
                success: function(response) {
                    console.log('API响应:', response);
                    
                    if (response.code === 200) {
                        showSuccess('生产计划修改成功！');
                        setTimeout(() => {
                            window.location.href = '/Home/GetProductionPlan';
                        }, 1500);
                    } else {
                        showError('修改失败：' + (response.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('API请求失败:', {xhr, status, error});
                    showError('请求失败：' + error);
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 表单验证
        function validateForm() {
            const requiredFields = [
                { id: 'planSubject', name: '计划主题' },
                { id: 'planOrderNumber', name: '计划单号' },
                { id: 'documentDate', name: '单据日期' },
                { id: 'expectedStartDate', name: '计划开始时间' },
                { id: 'expectedEndDate', name: '计划结束时间' },
                { id: 'planStatus', name: '计划状态' },
                { id: 'priority', name: '优先级' }
            ];

            for (let field of requiredFields) {
                const value = $(`#${field.id}`).val().trim();
                if (!value) {
                    showError(`请填写${field.name}`);
                    $(`#${field.id}`).focus();
                    return false;
                }
            }

            // 验证日期逻辑
            const startDate = new Date($('#expectedStartDate').val());
            const endDate = new Date($('#expectedEndDate').val());
            
            if (startDate >= endDate) {
                showError('计划结束时间必须晚于开始时间');
                $('#expectedEndDate').focus();
                return false;
            }

            return true;
        }

        // 收集表单数据
        function collectFormData() {
            const planId = parseInt($('#planId').val()) || 0;
            
            // 验证planId
            if (!planId || planId === 0) {
                showError('缺少计划ID，无法更新数据');
                return null;
            }
            
            const formData = {
                planId: planId,
                planSubject: $('#planSubject').val().trim(),
                planOrderNumber: $('#planOrderNumber').val().trim(),
                documentDate: new Date($('#documentDate').val()).toISOString(),
                remarks: $('#remarks').val().trim(),
                salesOrderNumber: $('#salesOrderNumber').val().trim(),
                relatedProjectName: $('#relatedProjectName').val().trim(),
                planStatus: parseInt($('#planStatus').val()),
                expectedStartDate: new Date($('#expectedStartDate').val()).toISOString(),
                expectedEndDate: new Date($('#expectedEndDate').val()).toISOString(),
                productionLine: $('#productionLine').val().trim(),
                priority: parseInt($('#priority').val()),
                productionItems: [],
                attachments: []
            };
            
            // console.log('收集的表单数据:', formData);
            // console.log('planId值:', planId);

            // 收集生产项目数据
            const usedPlanItemIds = new Set();
            $('#productionItemsBody tr').each(function() {
                const row = $(this);
                const planItemId = parseInt(row.find('input[name*="planItemId"]').val()) || 0;
                
                // 检查是否有重复的planItemId
                if (planItemId > 0 && usedPlanItemIds.has(planItemId)) {
                    console.warn('发现重复的planItemId:', planItemId);
                    return; // 跳过这个重复的项目
                }
                
                if (planItemId > 0) {
                    usedPlanItemIds.add(planItemId);
                }
                
                const item = {
                    planItemId: planItemId,
                    planId: parseInt(row.find('input[name*="planId"]').val()) || currentPlanId,
                    itemNumber: row.find('input[name*="itemNumber"]').val().trim(),
                    itemName: row.find('input[name*="itemName"]').val().trim(),
                    specificationModel: row.find('input[name*="specificationModel"]').val().trim(),
                    unit: row.find('input[name*="unit"]').val().trim(),
                    itemCategory: row.find('input[name*="itemCategory"]').val().trim(),
                    itemClassification: row.find('input[name*="itemClassification"]').val().trim(),
                    brand: row.find('input[name*="brand"]').val().trim(),
                    quantity: parseInt(row.find('input[name*="quantity"]').val()) || 0,
                    plannedQuantity: parseInt(row.find('input[name*="plannedQuantity"]').val()) || 0,
                    completedQuantity: parseInt(row.find('input[name*="completedQuantity"]').val()) || 0,
                    sortOrder: parseInt(row.find('input[name*="sortOrder"]').val()) || 0
                };
                
                // console.log('生产项目数据:', item);
                
                // 只添加有内容的项目
                if (item.itemNumber || item.itemName) {
                    formData.productionItems.push(item);
                }
            });

            // 收集附件数据
            $('#attachmentsBody tr').each(function() {
                const row = $(this);
                const attachment = {
                    attachmentId: parseInt(row.find('input[name*="attachmentId"]').val()) || 0,
                    planId: parseInt(row.find('input[name*="planId"]').val()) || currentPlanId,
                    fileName: row.find('input[name*="fileName"]').val().trim(),
                    fileSize: parseInt(row.find('input[name*="fileSize"]').val()) || 0,
                    filePath: row.find('input[name*="filePath"]').val().trim(),
                    fileType: row.find('input[name*="fileType"]').val().trim(),
                    uploadDate: row.find('input[name*="uploadDate"]').val() ? new Date(row.find('input[name*="uploadDate"]').val()).toISOString() : new Date().toISOString(),
                    uploadBy: row.find('input[name*="uploadBy"]').val().trim()
                };
                
                // console.log('附件数据:', attachment);
                
                // 只添加有内容的附件
                if (attachment.fileName) {
                    formData.attachments.push(attachment);
                }
            });

            // console.log('最终收集的数据:', formData);
            return formData;
        }

        // 重置表单
        function resetForm() {
            if (confirm('确定要重置表单吗？所有修改将被清空。')) {
                loadPlanData();
            }
        }

        // 返回上一页
        function goBack() {
            if (confirm('确定要离开吗？未保存的修改将丢失。')) {
                window.location.href = '/Home/GetProductionPlan';
            }
        }

        // HTML转义函数
        function escapeHtml(text) {
            if (!text) return '';
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.toString().replace(/[&<>"']/g, function(m) { return map[m]; });
        }

        // 显示加载状态
        function showLoading() {
            // 在表单中显示加载状态
            const loadingHtml = `
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <div class="mt-2 text-muted">正在加载数据...</div>
                </div>
            `;
            $('.card-body').prepend(loadingHtml);
        }

        // 隐藏加载状态
        function hideLoading() {
            // 移除加载提示
            $('.card-body .text-center.py-4').remove();
        }

        // 显示成功消息
        function showSuccess(message) {
            if (typeof layui !== 'undefined' && layui.layer) {
                layui.layer.msg(message, {icon: 1});
            } else {
                alert(message);
            }
        }

        // 显示错误消息
        function showError(message) {
            if (typeof layui !== 'undefined' && layui.layer) {
                layui.layer.msg(message, {icon: 2});
            } else {
                alert(message);
            }
        }
    </script>
}